package com.hongxun.modules.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hongxun.common.utils.PageUtils;
import com.hongxun.common.utils.Query;
import com.hongxun.common.utils.R;
import com.hongxun.modules.bss.entity.DPictureEntity;
import com.hongxun.modules.bss.service.DPictureService;
import com.hongxun.modules.csg.entity.CScheduleEntity;
import com.hongxun.modules.csg.entity.CScheduleReportEntity;
import com.hongxun.modules.csg.service.CScheduleReportService;
import com.hongxun.modules.csg.service.CScheduleService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.util.TextUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * 项目进度
 * 
 * @author zkcn
 * @email youeremail@163.com
 * @date 2018-09-11 09:33:49
 */

@RestController
@RequestMapping("/rest/cschedule")
public class CScheduleRestController {
	@Autowired
	CScheduleService cScheduleService;
	@Autowired
	CScheduleReportService cScheduleReportService;
	@Autowired
	DPictureService dPictureService;
	@Value("${com.hongxun.IMAGEROTT}")
	private String ROOT;
	
	/**
	 * 获取项目进度
	 */
	@RequestMapping("/getInfo")
	public R getInfo(@RequestParam Map<String, Object> params){

		String pGuid = params.get("pGuid").toString();

		//1.记录信息
		Map<String , Object> cScheduleMap = new HashMap<>();
		String csSql = " and p_guid='"+pGuid+"'";
		cScheduleMap.put("filterSql",csSql);
		List<CScheduleEntity> cScheduleList = cScheduleService.queryList(cScheduleMap);

		//2.填报信息【一个项目对应多个进度填报】
		Map<String , Object> cScheduleReportMap = new HashMap<>();
		String whereCSR = " 1=1 and p_guid='"+pGuid+"'";
		cScheduleReportMap.put("filterSql",whereCSR);
		List<CScheduleReportEntity> cScheduleReportEntityList = cScheduleReportService.queryList(cScheduleReportMap);


		return R.ok().put("cScheduleList", JSON.toJSONString(cScheduleList))
					 .put("cScheduleReportList",JSON.toJSONString(cScheduleReportEntityList));
	}

	/**
	 * 同步
	 *
	 * @param params
	 */
	@RequestMapping("/addCSchedule")
	public R addCSchedule(@RequestParam Map<String , Object> params){
		Map<String , Object> addMap = new HashMap<>();
		//1.新增项目进度
		List<CScheduleEntity> cScheduleEntities = JSON.parseArray(params.get("cScheduleList").toString(),CScheduleEntity.class);
		if (cScheduleEntities != null ) {
			cScheduleService.insertOrReplaceOrDelete(cScheduleEntities);
		}

		//2.新增进度填报信息
		List<CScheduleReportEntity> cScheduleReportEntityList = JSON.parseArray(params.get("cScheduleReportList").toString(),CScheduleReportEntity.class);
		if (cScheduleReportEntityList != null ) {
			cScheduleReportService.insertOrReplaceOrDelete(cScheduleReportEntityList);
			//保存进度填报信息之后将更新时间返回保存到项目进度中

			for (CScheduleReportEntity cScheduleReportEntity : cScheduleReportEntityList) {
				if (!cScheduleReportEntity.getSRDatastate().equals("删除")){
					CScheduleEntity cScheduleEntity = cScheduleService.queryObject(cScheduleReportEntity.getSGuid());
					cScheduleEntity.setSTime(cScheduleReportEntity.getSRUpdatetime());
					cScheduleService.update(cScheduleEntity);
				}

			}

		}

		return R.ok();
	}





/*****************************  中间检查图片上传 ***********************************/


	/**
	 * 图片上传
	 *
	 * @param file
	 * @param params
	 * @return
	 */
	@RequestMapping("/uploadImg")
	public R fileUpLoad(@RequestParam("fileName") MultipartFile file, @RequestParam Map<String, Object> params) {
		File f = new File(ROOT);
		if (!f.exists()) f.mkdir();
		String sPhoto = params.get("photo").toString();
		List<DPictureEntity> pictureEntities = JSON.parseArray(sPhoto, DPictureEntity.class);
		try {
			setFile(pictureEntities, file);
			dPictureService.insertOrReplaceOrDelete(pictureEntities);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.ok();
	}


	/**
	 * 获取图片信息
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping("/getPhotoInfo")
	public R getPhotoInfo(@RequestParam Map<String , Object> params){

		String pGuid = params.get("pGuid").toString();
		String jd = params.get("photoType").toString();
		List<DPictureEntity> pictureEntities = new ArrayList<>();

		String pLabel ="";
		String where = " 1=1 ";

		if (jd.equals("1")) {
			pLabel = "进度";
			where += " and p_guid='"+pGuid+"' and p_status='施工' and p_label like '%"+pLabel+"%'";
		}else if(jd.equals("2")){
			pLabel = "材料";
			where += " and p_guid='"+pGuid+"' and p_status='施工' and p_label like '%"+pLabel+"%'";
		}else {
			pLabel = "检查";
			where += " and p_guid='"+pGuid+"' and p_status='施工' and p_label like '%"+pLabel+"%'";
		}

		Map<String  , Object> map = new HashMap<>();
		map.put("filterSql",where+" ");
		pictureEntities = dPictureService.queryList(map);

		return R.ok().put("dPictureEntityList",JSON.toJSONString(pictureEntities));
	}


	private void setFile(List<DPictureEntity> bean, MultipartFile attachment)
			throws IOException {
		File zipFile = null;
		if (attachment != null && attachment.getSize() > 0) {
			InputStream inputStream = null;
			try {
				inputStream = attachment.getInputStream();
				File tempDir = new File(ROOT);
				String uuid = UUID.randomUUID().toString();
				zipFile = new File(tempDir, uuid + ".zip");
				FileUtils.copyInputStreamToFile(inputStream, zipFile);
				// 解压文件
				unzip(zipFile, tempDir, bean);
				//TODO 图片插入数据库
			} catch (IOException e) {
				if (zipFile != null) {
					FileUtils.deleteQuietly(zipFile);
				}
				throw e;
			} finally {
				IOUtils.closeQuietly(inputStream);
			}
		}
	}

	boolean setBeanName(List<DPictureEntity> bean, String oldName, String newName) {
		for (DPictureEntity d : bean) {
			if (d.getPName().equals(oldName)) {//如果有，则先判断图片是否已经存在。
				if (!TextUtils.isEmpty(d.getPServeraddress()) && new File(ROOT + d.getPServeraddress()).exists()) {
					return true;
				} else {
					d.setPServeraddress(newName);
				}
			}
		}
		return false;
	}

	void unzip(File file, File dir, List<DPictureEntity> bean) throws IOException {
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(file, Charset.forName("UTF-8"));
			Enumeration<? extends ZipEntry> entries = zipFile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry zipEntry = entries.nextElement();
				long l = System.currentTimeMillis();
				String fileName = l + zipEntry.getName();
				if (!setBeanName(bean, zipEntry.getName(), fileName)) {
					File targetFile = new File(dir, fileName);
					if (!zipEntry.isDirectory()) {
						InputStream input = zipFile.getInputStream(zipEntry);
						FileUtils.copyInputStreamToFile(input, targetFile);
					} else {
						targetFile.mkdirs();
					}
				}
			}
		} catch (IOException e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(zipFile);
		}
	}
	
}
